#!/bin/bash

# 初始化环境变量
app_service="${app_service}"
app_service_port="${app_service_port:-3000}"
app_service_image="${app_service_image}"
app_service_container_name="${app_service_container_name}"
app_service_network="${app_service_network}"
app_service_docker_max_memory="${app_service_docker_max_memory:-1280M}"

check_container() {
  if docker ps --format '{{.Names}}' | grep -q "^${app_container_name}$"; then
    echo "容器存在!"
    return 0
  else
    echo "容器不存在!"
    return 1
  fi
}

run_service() {
  echo "下拉镜像"
  echo "docker pull ${app_service_image}"
  docker pull ${app_service_image}

  echo "创建网络"
  echo "docker network create --attachable --driver bridge ${app_service_network}"
  docker network create --attachable --driver bridge ${app_service_network} || true

  echo "清理旧容器"
  echo "docker rm -f ${app_service_container_name}"
  docker rm -f ${app_service_container_name} || true

  echo "创建配置目录"
  echo "mkdir -p ${config_path}"
  mkdir -p ${config_path}

  echo "复制配置文件"
  echo "rsync -a --ignore-existing ./release/config/* ${config_path}"
  rsync -a --ignore-existing ./release/config/* ${config_path}

  echo "启动容器"
  echo "docker run --name ${app_service_container_name} \
            --restart=always \
            --network ${app_service_network} \
            -p ${app_service_port}:3000 \
            -m ${app_service_docker_max_memory} \
            -d ${app_service_image}"
  docker run --name ${app_service_container_name} \
    --restart=always \
    --network ${app_service_network} \
    -p ${app_service_port}:3000 \
    -m ${app_service_docker_max_memory} \
    -d ${app_service_image}
}

clean_service() {
  echo "清除容器"
  echo "docker stop ${app_container_name}"
  docker stop ${app_container_name}
  echo "docker rm ${app_container_name}"
  docker rm ${app_container_name}
}

# 主逻辑
case $1 in
  check)
    check_container
    ;;
  run)
    run_service
    ;;
  rerun)
    clean_service
    run_service
    ;;
  clean)
    clean_service
    ;;
  *)
    echo "Usage: $0 {check|run|rerun|clean}"
    exit 1
    ;;
esac